import router from "@/router";

import { defineStore } from "pinia";
import { cloneDeep } from "lodash-es";
import { STORE_PREFIX } from "@/utils/constant";

export const useUserStore = defineStore(
  `${STORE_PREFIX}user_store`,
  () => {
    const token = ref<string>("");
    const chatToken = ref("");
    const tokenTime = ref<number>(0);

    const userInfo = ref<UserInfoMo | null>(null); // 房主信息

    const getToken = computed(() => token.value);
    const getChatToken = computed(() => chatToken.value);
    const getTokenTime = computed(() => Number(tokenTime.value));
    const getUserInfo = computed(() => userInfo.value);

    // 设置token
    const setToken = (v: string) => {
      token.value = v;
    };
    const setChatToken = (v: string) => {
      chatToken.value = v;
    };
    const setTokenTime = () => {
      tokenTime.value = Date.now();
    };
    // 设置用户信息
    const setUserInfo = (info: UserInfoMo | null) => {
      userInfo.value = cloneDeep(info);
    };

    // 退出登录
    const logout = async () => {
      try {
        window.refreshTokenTimer = null;
        clearInterval(window.refreshTokenTimer);
        token.value = "";
        chatToken.value = "";
        tokenTime.value = 0;
        userInfo.value = null;
        router.push("/login");
        location.reload();
      } catch (error) {
        console.log(error);
      }
    };

    // 请求用户信息
    const actionUserInfo = async () => {
      try {
        // TODO: 请求房主信息
      } catch (error) {
        console.log(error);
      }
    };
    // 请求用户余额
    const actionWalletInfo = async () => {
      try {
        // TODO: 请求用户余额
      } catch (error) {
        console.log(error);
      }
    };
    // 请求房间信息
    const actionRoomInfo = async () => {
      try {
        // TODO: 请求房间信息
      } catch (error) {
        console.log(error);
      }
    };

    return {
      token,
      chatToken,
      tokenTime,
      userInfo,

      getToken,
      getChatToken,
      getTokenTime,
      getUserInfo,

      setToken,
      setChatToken,
      setTokenTime,
      setUserInfo,
      logout,

      actionUserInfo,
      actionWalletInfo,
      actionRoomInfo
    };
  },
  {
    persist: {
      storage: localStorage
    }
  }
);
